#include "MyArray.h"

MyArray::MyArray(int n) {
    N = (n < 0) ? 0 : n; 
    p = (N > 0) ? new int[N] : nullptr;

    for (int i = 0; i < N; ++i) {
        p[i] = 0;
    }
}

MyArray::MyArray(const MyArray& other) {
    N = other.N;
    p = (N > 0) ? new int[N] : nullptr;

    for (int i = 0; i < N; ++i) {
        p[i] = other.p[i];
    }
}

MyArray::~MyArray() {
    delete[] p;
    p = nullptr; 
    N = 0;      
}

MyArray& MyArray::operator=(const MyArray& other) {
    if (this == &other) {
        return *this;
    }

    delete[] p;
    p = nullptr;
    N = 0;

    N = other.N;
    if (N > 0) {
        p = new int[N];
        for (int i = 0; i < N; ++i) {
            p[i] = other.p[i];
        }
    }

    return *this;
}

MyArray MyArray::merge(const MyArray& other) const {
    MyArray result(N + other.N); 
    int idx = 0;

    for (int i = 0; i < N; ++i) {
        result.p[idx++] = p[i];
    }

    for (int i = 0; i < other.N; ++i) {
        result.p[idx++] = other.p[i];
    }

    return result;
}

MyArray MyArray::add(const MyArray& other) const {
    int newSize = std::max(N, other.N);
    MyArray result(newSize);

    for (int i = 0; i < newSize; ++i) {
        int val1 = (i < N) ? p[i] : 0;   
        int val2 = (i < other.N) ? other.p[i] : 0; 
        result.p[i] = val1 + val2;
    }

    return result;
}

MyArray MyArray::subtract(const MyArray& other) const {
    int newSize = std::max(N, other.N);
    MyArray result(newSize);

    for (int i = 0; i < newSize; ++i) {
        int val1 = (i < N) ? p[i] : 0;
        int val2 = (i < other.N) ? other.p[i] : 0;
        result.p[i] = val1 - val2;
    }

    return result;
}

MyArray MyArray::multiply(const MyArray& other) const {
    int newSize = std::max(N, other.N);
    MyArray result(newSize);

    for (int i = 0; i < newSize; ++i) {
        int val1 = (i < N) ? p[i] : 0;
        int val2 = (i < other.N) ? other.p[i] : 0;
        result.p[i] = val1 * val2;
    }

    return result;
}

MyArray MyArray::divide(const MyArray& other) const {
    int newSize = std::max(N, other.N);
    MyArray result(newSize);

    for (int i = 0; i < newSize; ++i) {
        int val1 = (i < N) ? p[i] : 0;
        int val2 = (i < other.N) ? other.p[i] : 0;

        if (val2 == 0) {
            std::cerr << "警告：索引 " << i << " 处除数为0，结果设为0" << std::endl;
            result.p[i] = 0;
        }
        else {
            result.p[i] = val1 / val2; 
        }
    }

    return result;
}

int MyArray::getSize() const {
    return N;
}

int& MyArray::operator[](int index) {
    assert(index >= 0 && index < N && "数组索引越界");
    return p[index];
}

const int& MyArray::operator[](int index) const {
    assert(index >= 0 && index < N && "数组索引越界");
    return p[index];
}